package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @author Gallant
 * @create 2020-07-10 14:43
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    // 根据用户名查询用户对象
    public User findByUsername(String username) {
        // 先从用户表中将用户查出来
        User user = userDao.findByUsername(username);
        // 判断,如果没有查到,直接返回null
        if (user == null) {
            return null;
        }
        // 根据用户的id查询此用户都具有哪些角色
        Set<Role> roles = roleDao.findByUserId(user.getId());
        // 判断
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                // 根据角色id查询权限
                Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            // 将获取到的角色设置给此用户
            user.setRoles(roles);
        }
        return user;
    }
}
